//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2008-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.sales.restaurant;

import cn.ekuma.data.dao.ListKeyed;
import cn.ekuma.epos.bean.util.sale.TicketHelper;
import cn.ekuma.epos.businesslogic.PlaceUtil;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import com.openbravo.pos.base.AppLocal;
import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.base.AppView;
import com.openbravo.pos.forms.JRootApp;
import com.openbravo.bean.Place;
import com.openbravo.bean.sales.SharedTicketInfo;
import com.openbravo.bean.Tax;
import com.openbravo.bean.sales.Ticket;
import com.openbravo.bean.sales.TicketLine;
import com.openbravo.pos.payment.JPaymentKeyBoardSelectReceipt;
import com.openbravo.pos.payment.JPaymentSelect;
import com.openbravo.pos.printer.TicketParser;
import com.openbravo.pos.printer.TicketPrinterException;
import com.openbravo.pos.sales.TaxesException;
import com.openbravo.pos.sales.TaxesLogic;
import com.openbravo.pos.scripting.ScriptEngine;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.scripting.ScriptFactory;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JList;

import net.xeoh.plugins.base.PluginManager;

/**重新实现！
 *
 * @author  adrianromero
 */
public class JPlaceGroupSplit extends AbstractKeyBoardJDialog{
    JSimplePlaceGroup receiptone;
    JSimplePlaceGroup receipttwo;
    JSimplePlaceGroup selectReceipt;
    ArrayList<String> placeGroups;
    List<Place> allPlaces;
    
    AppView m_App;

    AbstractJTicketsBagRestaurant restaurantMap;

    String currentGroup;
    private I_DataLogicReceipts dlReceipts;
    protected I_DataLogicSales m_dlSales;
    private I_DataLogicSystem dlSystem;
    private JPaymentSelect paymentdialogreceipt;

    java.util.List<SharedTicketInfo> shardTickets;

    GroupListModel groupListModel;

    boolean mustReflush;
   /** Creates new form JCatalogKeyBoardDialog */
    public JPlaceGroupSplit(java.awt.Frame parent, boolean modal) {
        super(parent, modal);

    }

     /** Creates new form JTicketsBagSharedList 
      * @wbp.parser.constructor*/
    private  JPlaceGroupSplit(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
    }

    private void init(AbstractJTicketsBagRestaurant ticketBagRestaurantMap,I_DataLogicSystem dlSystem,PluginManager pmf) {
        initComponents();
        restaurantMap=ticketBagRestaurantMap;
        allPlaces=restaurantMap.m_aplaces;
        m_App=restaurantMap.getM_App();
        dlReceipts=restaurantMap.dlReceipts;
        m_dlSales=restaurantMap.getM_dlSales();
        this.dlSystem = dlSystem;

        getRootPane().setDefaultButton(m_jButtonOK);
        receiptone = new JSimplePlaceGroup();
        jPanel5.add(receiptone, BorderLayout.CENTER);

        receipttwo = new JSimplePlaceGroup();
        jPanel3.add(receipttwo, BorderLayout.CENTER);
        groupListModel=new GroupListModel();
        jPlaceGroupList.setModel(groupListModel);
        paymentdialogreceipt=JPaymentKeyBoardSelectReceipt.getDialog(this);
        paymentdialogreceipt.init(m_App, dlSystem, m_dlSales, pmf, restaurantMap.getTicketsEditor().getSecurityManager());
        mustReflush=false;
        reflush();
       
    }

     



    public static JPlaceGroupSplit getDialog(Component parent,I_DataLogicSystem dlSystem,PluginManager pmf) {

        Window window = getWindow(parent);

        JPlaceGroupSplit myreceiptsplit;

        if (window instanceof Frame) {
            myreceiptsplit = new JPlaceGroupSplit((Frame) window,true);
        } else {
            myreceiptsplit = new JPlaceGroupSplit((Dialog) window,true);
        }

        myreceiptsplit.init((AbstractJTicketsBagRestaurant)parent, dlSystem, pmf);
        return myreceiptsplit;
    }

    protected static Window getWindow(Component parent) {
        if (parent == null) {
            return new JFrame();
        } else if (parent instanceof Frame || parent instanceof Dialog) {
            return (Window) parent;
        } else {
            return getWindow(parent.getParent());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel6 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jGroupName = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        jNewGroup = new javax.swing.JButton();
        jRemoveGroup = new javax.swing.JButton();
        jPaymentGroup = new javax.swing.JButton();
        m_jButtonOK = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPlaceGroupList = new javax.swing.JList();
        jPanel10 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jBtnToRightOne = new javax.swing.JButton();
        jBtnToLeftOne = new javax.swing.JButton();
        jBtnToLeftAll = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(AppLocal.getIntString("caption.split")); // NOI18N
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jPanel6.setLayout(new java.awt.BorderLayout());

        jPanel8.setLayout(new javax.swing.BoxLayout(jPanel8, javax.swing.BoxLayout.LINE_AXIS));

        jLabel1.setText(AppLocal.getIntString("label.newGroupName")); // NOI18N
        jLabel1.setPreferredSize(new java.awt.Dimension(80, 15));
        jPanel8.add(jLabel1);

        jGroupName.setEnabled(false);
        jPanel8.add(jGroupName);

        jPanel6.add(jPanel8, java.awt.BorderLayout.CENTER);

        jNewGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editnew.png"))); // NOI18N
        jNewGroup.setFocusable(false);
        jNewGroup.setMargin(new java.awt.Insets(8, 16, 8, 16));
        jNewGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jNewGroupActionPerformed(evt);
            }
        });
        jPanel9.add(jNewGroup);

        jRemoveGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editdelete.png"))); // NOI18N
        jRemoveGroup.setFocusable(false);
        jRemoveGroup.setMargin(new java.awt.Insets(8, 16, 8, 16));
        jRemoveGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRemoveGroupActionPerformed(evt);
            }
        });
        jPanel9.add(jRemoveGroup);

        jPaymentGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/inbox.png"))); // NOI18N
        jPaymentGroup.setFocusable(false);
        jPaymentGroup.setMargin(new java.awt.Insets(8, 16, 8, 16));
        jPaymentGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPaymentGroupActionPerformed(evt);
            }
        });
        jPanel9.add(jPaymentGroup);

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/redo16.png"))); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel9.add(m_jButtonOK);

        jPanel6.add(jPanel9, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel6, java.awt.BorderLayout.NORTH);

        jPanel7.setLayout(new java.awt.BorderLayout());

        jPlaceGroupList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jPlaceGroupList.setPreferredSize(new java.awt.Dimension(120, 85));
        jPlaceGroupList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jPlaceGroupListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jPlaceGroupList);

        jPanel7.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel7, java.awt.BorderLayout.CENTER);

        jPanel10.setPreferredSize(new java.awt.Dimension(400, 418));
        jPanel10.setLayout(new java.awt.CardLayout());

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));

        jPanel5.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jPanel5);

        jPanel4.setLayout(new java.awt.GridBagLayout());

        jBtnToRightOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1rightarrow.png"))); // NOI18N
        jBtnToRightOne.setFocusPainted(false);
        jBtnToRightOne.setFocusable(false);
        jBtnToRightOne.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jBtnToRightOne.setRequestFocusEnabled(false);
        jBtnToRightOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnToRightOneActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel4.add(jBtnToRightOne, gridBagConstraints);

        jBtnToLeftOne.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1leftarrow.png"))); // NOI18N
        jBtnToLeftOne.setFocusPainted(false);
        jBtnToLeftOne.setFocusable(false);
        jBtnToLeftOne.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jBtnToLeftOne.setRequestFocusEnabled(false);
        jBtnToLeftOne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnToLeftOneActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel4.add(jBtnToLeftOne, gridBagConstraints);

        jBtnToLeftAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/2leftarrow.png"))); // NOI18N
        jBtnToLeftAll.setFocusPainted(false);
        jBtnToLeftAll.setFocusable(false);
        jBtnToLeftAll.setMargin(new java.awt.Insets(8, 14, 8, 14));
        jBtnToLeftAll.setRequestFocusEnabled(false);
        jBtnToLeftAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnToLeftAllActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel4.add(jBtnToLeftAll, gridBagConstraints);

        jPanel1.add(jPanel4);

        jPanel3.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jPanel3);

        jPanel10.add(jPanel1, "card9");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        jPanel11.add(jScrollPane2);

        jPanel10.add(jPanel11, "card3");

        getContentPane().add(jPanel10, java.awt.BorderLayout.EAST);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-585)/2, (screenSize.height-470)/2, 585, 470);
    }// </editor-fold>//GEN-END:initComponents

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonOKActionPerformed
        clear();
        dispose();
    }//GEN-LAST:event_m_jButtonOKActionPerformed

    private void jBtnToRightOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnToRightOneActionPerformed
       if(currentGroup!=null){
           mustReflush=true;
           Place[] lines =receiptone.getSelectedLines();
           changePlaceGroup(lines,currentGroup);
           receipttwo.addSelectedLines(lines);
           receiptone.removeLines(lines);
       }
}//GEN-LAST:event_jBtnToRightOneActionPerformed

    private void jBtnToLeftOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnToLeftOneActionPerformed
       if(currentGroup!=null){
          Place[] lines = receipttwo.getSelectedLines();
          if(lines.length>0){
            mustReflush=true;
            changePlaceGroup(lines,null);
            receiptone.addSelectedLines(lines);
            receipttwo.removeLines(lines);
          }
       }
}//GEN-LAST:event_jBtnToLeftOneActionPerformed


    private void jBtnToLeftAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnToLeftAllActionPerformed
       if(currentGroup!=null){

          Place[] lines = receipttwo.getSelectedLines();
          if(lines.length>0){
             mustReflush=true;
             changePlaceGroup(lines,null);
             receiptone.addSelectedLines(lines);
             receipttwo.removeLines(lines);
          }
       }
}//GEN-LAST:event_jBtnToLeftAllActionPerformed

    private void jPlaceGroupListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jPlaceGroupListValueChanged
       
          if(evt.getValueIsAdjusting())   
                ;//ignore   this   event   if   users   still   adjust   his/her   selection   
          else   
          {
            currentGroup=(String) ((JList)evt.getSource()).getSelectedValue();
            reflushGroup();
           }
    }//GEN-LAST:event_jPlaceGroupListValueChanged




     /**
     * 刷新当前选择,结组进行重
     * @param toString
     */
    private void reflush() {
         placeGroups=new ArrayList<String>();
         currentGroup=null;
         //receiptone.refush(PlaceUtil.getPlacesForState(allPlaces, Place.PLACESTATE_empty,false));
         for(Place place:allPlaces){
             // if(place.isGroupPlace()){
             //    String groupName=place.getM_sGroupName();
             //     if(!placeGroups.contains(groupName))
             //         placeGroups.add(groupName);
             // }
         }
        groupListModel.reSet(placeGroups);
        if(placeGroups.size()>0)
             jPlaceGroupList.setSelectedIndex(0);
    }

    private void changePlaceGroup(Place[] lines,String groupName){
        if (lines != null) {
           // for(Place place:lines)
           //     place.setM_sGroupName(groupName);
            savePalces(lines);
        }
    }

    private void savePalces(Place[] places){
        for(Place place:places){
            savePlace(place);
        }
    }

    private void savePlace(Place place){
       // try {
        //    m_dlSales.updatePlace(place.getId(), place);
       // } catch (BasicException ex) {
          //  Logger.getLogger(JPlaceGroupSplit.class.getName()).log(Level.SEVERE, null, ex);
        //}
    }

     private void reflushGroup() {
        /*if(currentGroup!=null){
          receipttwo.refush(PlaceUtil.getPlacesForGroupName(allPlaces, currentGroup));
          jGroupName.setText(currentGroup);
        }else{
            receipttwo.refush(null);
            jGroupName.setText("");
        }*/

    }

    /**
     *结算当前组单
     * @param evt
     */
    private void jPaymentGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPaymentGroupActionPerformed
 
          if(currentGroup==null)
              return;
          java.util.List<Ticket> groupTickets=getGroupTickets();
          Ticket ticket=mergeTickets(groupTickets);
          ticket.setProperty(Ticket.AUTOCREATE_NAME, currentGroup);
          if(TicketHelper.getTotal(ticket)==0.0)
              return;
          if(closeTicket(ticket, currentGroup)){
              mustReflush=true; 
              List<Place> lines = receipttwo.getPlaces();
              Place[] places=new Place[lines.size()];
              lines.toArray(places);
              changePlaceGroup(places,null);
             // for(Place place:places){
             //     place.setPeople(false);
             // }
              receiptone.addSelectedLines(places);
              groupListModel.remove(currentGroup);
            //  removeSherdTickets(lines);
              currentGroup=null;
              reflushGroup();
          }
    }//GEN-LAST:event_jPaymentGroupActionPerformed

    private void jNewGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jNewGroupActionPerformed
        JNewGroupDialog newGroupDialg=JNewGroupDialog.getDialog(this);
        newGroupDialg.setVisible(true);
        if(newGroupDialg.isOK()){
            if(groupListModel.isContains(newGroupDialg.getGroupName())){
                MessageInf msg = new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.groupnamealreadyused"));
                msg.show(this);
            }else{
            currentGroup=newGroupDialg.getGroupName();
            groupListModel.addGroupName(currentGroup);
            reflushGroup();
            }
        }
    }//GEN-LAST:event_jNewGroupActionPerformed

    private void jRemoveGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRemoveGroupActionPerformed
       if(currentGroup!=null){
           List<Place> lines = receipttwo.getPlaces();
           Place[] places=new Place[lines.size()];
           lines.toArray(places);
           changePlaceGroup(places,null);
           receiptone.addSelectedLines(places);
           groupListModel.remove(currentGroup);
           currentGroup=null;
           reflushGroup();
        }
    }//GEN-LAST:event_jRemoveGroupActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnToLeftAll;
    private javax.swing.JButton jBtnToLeftOne;
    private javax.swing.JButton jBtnToRightOne;
    private javax.swing.JTextField jGroupName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jNewGroup;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JButton jPaymentGroup;
    private javax.swing.JList jPlaceGroupList;
    private javax.swing.JButton jRemoveGroup;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton m_jButtonOK;
    // End of variables declaration//GEN-END:variables


    

    private List<Ticket> getGroupTickets(){
       List<Place> groupPlace=receipttwo.getPlaces();
       java.util.List<Ticket> groupTickets=new ArrayList<Ticket>();
       for(Place place:groupPlace){
              Ticket tempTicket = getTicketInfo(place);
              if(tempTicket!=null){
                  groupTickets.add(tempTicket);
              }
       }
       return groupTickets;
    }

    protected Ticket getTicketInfo(Place place) {
        try {
            return dlReceipts.getSharedTicket(place.getId());
        } catch (BasicException e) {
            new MessageInf(e).show(this);
            return null;
        }
    }


    private Ticket mergeTickets(List<Ticket> tickets){
        Ticket ticket=new Ticket();
        for(Ticket ticketclip:tickets){
             for(TicketLine line : ticketclip.getLines()) {
                   ticket.addLine(line);
              }
        }
        return ticket;
    }

    public java.util.List<SharedTicketInfo> loadTickets() {
       java.util.List<SharedTicketInfo> l;
        try {
             l = dlReceipts.getSharedTicketList(m_App.getInventoryLocation());
        } catch (BasicException e) {
            new MessageInf(e).show(this);
            l=new ArrayList();
        }
        return l;
    }

    private void removeSherdTickets(List<Place> tickets){
        for(Place ticket:tickets){
          try {
              dlReceipts.deleteSharedTicket(ticket.getId());
        } catch (BasicException e) {
              new MessageInf(e).show(this);
        }
        }
    }

    private boolean closeTicket(Ticket ticket, Object ticketext) {
        boolean resultok = false;
        ticket.setHostName(m_App.getProperties().getHost());
        if ( restaurantMap.getTicketsEditor().getSecurityManager().hasPermissionByName("sales.Total")) {
            try {
                java.util.List<Tax> taxlist = m_dlSales.list(Tax.class);
                ListKeyed taxcollection = new ListKeyed<Tax>(taxlist);
                TaxesLogic taxeslogic= new TaxesLogic(taxlist);
                // reset the payment info
                taxeslogic.calculateTaxes(ticket);
                if (TicketHelper.getTotal(ticket)>=0.0){
                    ticket.resetPayments(); //Only reset if is sale
                }

                //if (executeEvent(ticket, ticketext, "ticket.total") == null) {

                    // Muestro el total
                    printTicket("Printer.TicketTotal", ticket, ticketext,taxcollection,taxeslogic);

                    paymentdialogreceipt.setPrintSelected(true);

                    paymentdialogreceipt.setTransactionID(TicketHelper.getTransactionID(ticket));

                    if (paymentdialogreceipt.showDialog(TicketHelper.getTotal(ticket), ticket.getCustomer())) {

                        // assign the payments selected and calculate taxes.
                        ticket.setPayments(paymentdialogreceipt.getSelectedPayments());

                        // Asigno los valores definitivos del ticket...
                        ticket.setUser(m_App.getAppUserView().getUser().getUserInfo()); // El usuario que lo cobra
                        ticket.setActiveCash(m_App.getUserCashIndex());
                        ticket.setDate(new Date()); // Le pongo la fecha de cobro

                        //if (executeEvent(ticket, ticketext, "ticket.save") == null) {
                            // Save the receipt and assign a receipt number
                            try {
                                m_dlSales.saveTicket(ticket, m_App.getInventoryLocation());
                            } catch (BasicException eData) {
                                MessageInf msg = new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.nosaveticket"), eData);
                                msg.show(this);
                            }

                            //executeEvent(ticket, ticketext, "ticket.close", new ScriptArg("print", paymentdialog.isPrintSelected()));

                            // Print receipt.
                            printTicket(paymentdialogreceipt.isPrintSelected()
                                    ? "Printer.Ticket"
                                    : "Printer.Ticket2", ticket, ticketext,taxcollection,taxeslogic);
                            resultok = true;
                        //}
                    }
                //}
            } catch (BasicException ex) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
                msg.show(this);
                resultok = false;
            } catch (TaxesException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
                msg.show(this);
                resultok = false;
            }
        }
        return resultok;
    }

    private void printTicket(String sresourcename, Ticket ticket, Object ticketext, ListKeyed taxcollection,TaxesLogic taxeslogic) {
        String sresource = dlSystem.getResourceAsXML(sresourcename);
        if (sresource == null) {
            MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotprintticket"));
            msg.show(this);
        } else {
            try {
                TicketParser m_TTP=new TicketParser(((JRootApp)m_App).getDeviceTicket(), dlSystem);
                ScriptEngine script = ScriptFactory.getScriptEngine(ScriptFactory.VELOCITY);
                script.put("taxes", taxcollection);
                script.put("taxeslogic", taxeslogic);
                script.put("ticket", ticket);
                script.put("place", ticketext);
                m_TTP.printTicket(script.eval(sresource).toString());
            } catch (ScriptException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotprintticket"), e);
                msg.show(this);
            } catch (TicketPrinterException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotprintticket"), e);
                msg.show(this);
            }
        }
    }

    private void clear() {
       restaurantMap=null;
        allPlaces=null;
        m_App=null;
        dlReceipts=null;
        m_dlSales=null;
        dlSystem = null;
        receiptone = null;
        receipttwo =null;
        groupListModel=null;
        paymentdialogreceipt=null;
    }


    class GroupListModel extends javax.swing.AbstractListModel{
        List<String> groupList;

        private GroupListModel() {
            groupList=new ArrayList();
        }

        public void reSet(List<String> List){
            groupList=List;
            if(groupList==null)
                groupList=new ArrayList();
        }

        @Override
        public int getSize() {
            return groupList.size();
        }

        @Override
        public Object getElementAt(int index) {
            return groupList.get(index);
        }

        public void addGroupName(String groupName){
            groupList.add(groupName);
            fireIntervalAdded(groupName, groupList.size()-1, groupList.size()-1);
        }
        
        public void removeGroupName(int index){
            fireIntervalRemoved(groupList.get(index), index, index);
            groupList.remove(index);
        }

        public boolean isContains(String groupName){
            return groupList.contains(groupName);
        }

        private void remove(String groupName) {
            if(groupList.contains(groupName)){
                removeGroupName(groupList.indexOf(groupName));
            }
        }
    }

    public boolean isMustReflush() {
        return mustReflush;
    }

    @Override
    protected void enterKeyProc() {
        clear();
        dispose();
    }

    @Override
    protected void escapeKeyProc() {
        clear();
        dispose();
    }

    @Override
    protected void upKeyProc() {
        if (selectReceipt == null) {
            selectReceipt = receiptone;
        }
        selectReceipt.selectUpIndex();
    }

    @Override
    protected void downKeyProc() {
        if (selectReceipt == null) {
            selectReceipt = receiptone;
        }
        selectReceipt.selectDownIndex();
    }
    // End of variables declaration
}
